<?php

namespace App\Servers\WebSocket;

use App\Servers\WebSocket\EventLoop\BroadCast;
use App\Servers\WebSocket\Utils\Factory;
use App\Servers\WebSocket\Utils\Response;

class EventHandler extends \Jammiest\SwigeCore\Handlers\EventHandler
{
    public function onOpen($ws, $request)
    {
        echo "New connection established: {$request->fd}" . PHP_EOL;
        $ws->push($request->fd, Response::getInstance()->data('', ['建立连接'])->end());
        (new BroadCast($this->container, $ws))->loop();
    }

    public function onMessage($ws, $frame)
    {
        $ws->push($frame->fd, Factory::getInstance()->dispatch(json_decode($frame->data), $this->container, $frame->fd));
    }
}
